package com.informationsystem.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.informationsystem.service.InformationManager;
import com.informationsystem.dao.SearchException;
import com.informationsystem.model.Information;
import com.informationsystem.webapp.action.BaseAction;

import java.util.List;

public class InformationAction extends BaseAction implements Preparable {
    private InformationManager informationManager;
    private List informations;
    private Information information;
    private Long id;
    private String query;

    public void setInformationManager(InformationManager informationManager) {
        this.informationManager = informationManager;
    }

    public List getInformations() {
        return informations;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String informationId = getRequest().getParameter("information.id");
            if (informationId != null && !informationId.equals("")) {
                information = informationManager.get(new Long(informationId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        try {
            informations = informationManager.search(query, Information.class);
        } catch (SearchException se) {
            addActionError(se.getMessage());
            informations = informationManager.getAll();
        }
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Information getInformation() {
        return information;
    }

    public void setInformation(Information information) {
        this.information = information;
    }

    public String delete() {
        informationManager.remove(information.getId());
        saveMessage(getText("information.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            information = informationManager.get(id);
        } else {
            information = new Information();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (information.getId() == null);

        informationManager.save(information);

        String key = (isNew) ? "information.added" : "information.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}